package jmauth

import (
	"log"
	"net/url"
	"path"
)

var (
	//权限组=>权限URI
	groupURL = map[string][]string{
		"epg.mgr":    []string{"/*", "/*/*", "/*/*/*", "/*/*/*/*"},
		"epg.view":   []string{"/", "/admin/index", "/admin/logs/*", "/admin/stats/*"},
		"epg.config": []string{"/", "/admin/index", "/admin/logs/*", "/admin/stats/*", "/admin/setting/*"},
		"epg.consul": []string{"/", "/admin/index", "/admin/logs/*", "/admin/stats/*", "/admin/setting/consul"},
		"epg.api":    []string{"/", "/admin/index", "/admin/logs/*", "/admin/stats/*", "/admin/api/*"},
	}
)

type authConfig struct {
	AppName  string
	AppKey   string
	CBUrl    string
	Host     string
	urlAuth  string
	urlInfo  string
	urlPriv  string
	groupURL map[string][]string
}

func newAuthConfig(appName, appKey, host, cbURL string) *authConfig {
	ac := &authConfig{
		AppName:  appName,
		AppKey:   appKey,
		Host:     host,
		CBUrl:    cbURL,
		urlAuth:  host + "api/login/?camefrom=" + appName + "&login_url=" + url.QueryEscape(cbURL),
		urlInfo:  host + "api/info/?session_id=",
		urlPriv:  host + "api/grouprole/?app_key=" + appKey + "&app_name=" + appName + "&uid=",
		groupURL: groupURL,
	}
	return ac
}

func (ac *authConfig) getAuthURL() string {
	return ac.urlAuth
}

func (ac *authConfig) getInfoURL(sessid string) string {
	return ac.urlInfo + sessid
}

func (ac *authConfig) getPrivURL(uid string) string {
	return ac.urlPriv + uid
}

func (ac *authConfig) hasPriv(group []string, p string) bool {
	for _, grp := range group {
		g, ok := ac.groupURL[grp]
		if !ok {
			continue
		}
		for _, v := range g {
			if m, _ := path.Match(v, p); m {
				log.Println("hasPriv: true")
				return true
			}
		}
	}
	log.Println("hasPriv: false")
	return false
}
